﻿namespace IBTrader.Modules.Log
{
    using AxTWSLib;
    using NLog;

    public class IBLog
    {
        private int lastErrorCode;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        //internal void Write(object sender, _DTwsEvents_execDetailsExEvent e)
        //{
        //    if (e.reqId != Executions.Id && e.reqId != ExecutionsMissed.Id && e.execution.clientId == Properties.Settings.Default.TwsClientId)
        //        logger.Info("execDetailsEx OrderId {1} {2} {3}", e.reqId, e.execution.orderId, e.execution.side, e.execution.avgPrice);
        //}
        public void Write(object _, _DTwsEvents_errMsgEvent e)
        {
            var logLevel = LogLevel.Info;

            switch (e.errorCode)
            {
                //case 103: // Duplicate order id
                //    // happened to child orders after parent order filled? and connection lost - restored
                //    if (CancelOrder != null) CancelOrder(this, new Order.OrderArgs { OrderId = e.id });
                //    break;
                //case 135: // Can't find order with id
                //    if (MissingOrder != null) MissingOrder(this, new Order.OrderArgs { OrderId = e.id });
                //    break;
                case 202: // Order cancelled - Reason:
                    logLevel = LogLevel.Debug;
                    break;
                case 1102: // Connectivity between IB and TWS has been restored - data maintained. 
                case 2104: // Market data farm connection is OK:cusfuture
                case 2106: // HMDS data farm connection is OK:ushmds2a 
                case 2107: // HMDS data farm connection is inactive but should be available upon demand.ushmds2a 
                case 2108: // Market data farm connection is inactive but should be available upon demand.cusfuture
                    //if (e.errorCode == 2104 && MarketRestart != null) MarketRestart(this, EventArgs.Empty);
                    if (lastErrorCode != e.errorCode) logger.Info("+");
                    logLevel = lastErrorCode == e.errorCode ? LogLevel.Trace : LogLevel.Debug;
                    break;

                case 1100: // Connectivity between IB and TWS has been lost.
                case 2103: // Market data farm connection is broken:cusfuture 
                case 2105: // HMDS data farm connection is broken:ushmds2a
                case 2119: // Market data farm is connecting:cusfuture 
                    if (lastErrorCode != e.errorCode) logger.Info("-");
                    logLevel = lastErrorCode == e.errorCode ? LogLevel.Trace : LogLevel.Debug;
                    break;
            }

            lastErrorCode = e.errorCode;
            logger.Log(logLevel, "{0} {1} : id {2}", e.errorCode, e.errorMsg, e.id);
        }
    }
}